import elasticsearch7

from config.secure import ES_URI_SMALL, PORT_SMALL, ES_URI, USERNAME, PASSWORD, PORT


class SmallES():
    es_small = elasticsearch7.Elasticsearch([ES_URI_SMALL], port=PORT_SMALL)
    es = elasticsearch7.Elasticsearch([ES_URI], http_auth=(USERNAME, PASSWORD), port=PORT)

    def makerQuery(self, source):
        query = {
            "query": {
                "bool": {
                    "must": []
                }
            }
        }
        for key in source.keys():
            query['query']['bool']['must'].append({
                "match_phrase": {
                    key: source[key]
                }
            })
        return query

    def insertPolymerize(self, source, index, target_index):
        query = self.makerQuery(source)
        searchResponse = self.es.search(body=query, index=index, size=200)
        if searchResponse['hits']['total']['value'] > 0:
            bulk_source = searchResponse['hits']['hits']
            self.bulk2smalles(bulk_source, target_index)


    def Q2B(self, uchar):
        """单个字符 全角转半角"""
        inside_code = ord(uchar)
        if inside_code == 0x3000:
            inside_code = 0x0020
        else:
            inside_code -= 0xfee0
        if inside_code < 0x0020 or inside_code > 0x7e:  # 转完之后不是半角字符返回原来的字符
            return uchar
        return chr(inside_code)


    def stringQ2B(self, ustring):
        """把字符串全角转半角"""
        return "".join([self.Q2B(uchar) for uchar in ustring])


    def bulk2smalles(self, bulk_source, target_index):
        body = []
        base_source = {}
        for key in bulk_source[0]['_source'].keys():
            if key != 'content':
                base_source[key] = bulk_source[0]['_source'][key]
        for item in bulk_source:
            itemLength = len(item['_source']['content'])
            sliceTotal = int(itemLength / 300) + 1
            for i in range(sliceTotal):
                item_source = base_source.copy()
                start = i * 300
                end = start + 400
                if end > itemLength:
                    end = itemLength
                sliceContent = item['_source']['content'][start:end]
                item_source['content'] = self.stringQ2B(sliceContent.replace(" ", ""))
                createBody = {"index": {"_index": target_index}}
                body.append(createBody)
                body.append(item_source)
        try:
            self.es_small.bulk(body=body, index=target_index, refresh=True, request_timeout=200)
        except Exception as e:
            print(e)
